import cgi
import datetime
import urllib
import webapp2
import jinja2
import os

from google.appengine.ext import db
from google.appengine.api import users

jinja_environment = jinja2.Environment(
	loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

# The following defines a data model for a greeting.
class Greeting(db.Model):
  """Models an individual Guestbook entry with an author, content, and date."""
  author = db.StringProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)
  # This defines a Greeting model with three properties:
  # author whose value is a string, content whose value is another string,
  # and date whose value is a datetime.datetime.

def guestbook_key(guestbook_name=None):
  """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
  return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')


class MainPage(webapp2.RequestHandler):
  def get(self):
    guestbook_name=self.request.get('guestbook_name')
    greetings_query = Greeting.all().ancestor(
                        guestbook_key(guestbook_name)).order('-date')
    greetings = greetings_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'greetings': greetings,
      'guestbook_name':guestbook_name, 
      'guestbook': urllib.urlencode({'guestbook_name': guestbook_name}),
      'url': url,
      'url_linktext': url_linktext,
    }

    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))


# Creates new greetings and saves them to the Datastore
class Guestbook(webapp2.RequestHandler):
  def post(self):
    # We set the same parent key on the 'Greeting' to ensure each greeting is in
    # the same entity group. Queries across the single entity group will be
    # consistent. However, the write rate to a single entity group should
    # be limited to ~1/second.
    guestbook_name = self.request.get('guestbook_name')
    greeting = Greeting(parent=guestbook_key(guestbook_name))

    user = users.get_current_user()
    if user:
      greeting.author = user.nickname()
    # Else we allow anonymous greetings.

    greeting.content = self.request.get('content')

    # Finally, greeting.put() saves our new object to the Datastore. 
    # If we had acquired this object from a query, put() would have updated the 
    # existing object. Since we created this object with the model constructor, 
    # put() adds the new object to the Datastore.
    greeting.put()

    self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))


def datetimeformat(value, format='%m-%d-%Y at %H:%M'):
	return value.strftime(format)

# Add/register datetimeformat as a Jinja2 filter by updating the filters dict
# on the jinja environment:
jinja_environment.filters['datetimeformat'] = datetimeformat

myapp = webapp2.WSGIApplication([('/', MainPage),
                                ('/sign', Guestbook)],
                                debug=True)
